import React, { useState, useRef, useEffect } from 'react';
import { Container, Box, Fab, Snackbar, Alert } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import { PostProvider, usePost } from '../features/community/contexts/PostContext';
import { PostList } from '../features/community/components/PostList';
import { EditPostDialog } from '../features/community/components/EditPostDialog';
import { CreatePostDialog } from '../features/community/components/CreatePostDialog';
import { Post } from '../features/community/types';
import { useLocation } from 'react-router-dom';
import { PostService } from '../features/community/services/PostService';

// 创建一个内部组件来使用 usePost hook
const CommunityPageContent: React.FC = () => {
  const { posts } = usePost();
  const [editingPost, setEditingPost] = useState<Post | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  
  // 添加操作反馈状态
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('success');
  
  // 使用 ref 来存储 PostList 组件的方法
  const postListRef = useRef<{ handleOpenModal: (post: Post) => void } | null>(null);
  
  // 获取路由状态，检查是否有选中的帖子ID
  const location = useLocation();

  useEffect(() => {
    // 检查路由状态中是否有选中的帖子ID
    const state = location.state as { selectedPostId?: number } | null;
    if (state?.selectedPostId && postListRef.current) {
      // 获取帖子详情并显示
      const fetchPostDetail = async () => {
        try {
          const post = await PostService.getPostById(state.selectedPostId);
          if (post && postListRef.current) {
            // 使用 PostList 中的模态框显示详情
            postListRef.current.handleOpenModal(post);
          }
        } catch (error) {
          console.error('获取帖子详情失败:', error);
          showFeedback('获取帖子详情失败，请重试', 'error');
        }
      };
      
      fetchPostDetail();
    }
  }, [location.state, postListRef.current]);

  const handleEditPost = (postId: number) => {
    // 从 posts 数组中找到对应的帖子
    const post = posts.find(p => p.postId === postId);
    if (post) {
      setEditingPost(post);
    }
  };
  
  // 处理关闭 Snackbar
  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
  };
  
  // 显示操作反馈
  const showFeedback = (message: string, severity: 'success' | 'error' | 'info' | 'warning' = 'success') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        <PostList 
          onEditPost={handleEditPost} 
          ref={postListRef}
        />
        <EditPostDialog
          open={Boolean(editingPost)}
          post={editingPost}
          onClose={(edited?: boolean, updatedPost?: Post) => {
            // 如果编辑成功，显示编辑后的帖子详情并显示反馈
            if (edited && updatedPost && postListRef.current) {
              // 使用 PostList 中的模态框显示详情
              postListRef.current.handleOpenModal(updatedPost);
              // 显示编辑成功反馈
              showFeedback('帖子编辑成功！', 'success');
            }
            setEditingPost(null);
          }}
        />
        <CreatePostDialog
          open={isCreateDialogOpen}
          onClose={(created?: boolean) => {
            setIsCreateDialogOpen(false);
            if (created) {
              // 显示创建成功反馈
              showFeedback('帖子发布成功！', 'success');
            }
          }}
        />
        
        <Fab
          color="primary"
          aria-label="add"
          onClick={() => setIsCreateDialogOpen(true)}
          sx={{
            position: 'fixed',
            bottom: 16,
            right: 16,
          }}
        >
          <AddIcon />
        </Fab>
        
        {/* 操作反馈提示 */}
        <Snackbar
          open={snackbarOpen}
          autoHideDuration={3000}
          onClose={handleSnackbarClose}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        >
          <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
            {snackbarMessage}
          </Alert>
        </Snackbar>
      </Box>
    </Container>
  );
};

// 导出包装了 PostProvider 的主组件
export const CommunityPage: React.FC = () => {
  return (
    <PostProvider>
      <CommunityPageContent />
    </PostProvider>
  );
};